<script setup lang="ts">
import { getPostList, likePost, unlikePost } from '@/api/post'
import { onMounted, ref } from 'vue'

// 搜索关键词
const searchKeyword = ref('')

// 分类数据
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '推荐' },
  { id: 2, name: '最新' },
  { id: 3, name: '热门' },
])

// 当前选中的分类
const currentCategory = ref(0)

// 帖子列表数据
const posts = ref([
])

// 是否还有更多数据
const hasMore = ref(true)

// 页码
const page = ref(1)

// 搜索处理
function handleSearch() {
  page.value = 1
  loadPosts()
}

// 选择分类
function selectCategory(categoryId: number) {
  currentCategory.value = categoryId
  page.value = 1
  loadPosts()
}

// 跳转到详情页
function goToDetail(postId: number) {
  uni.navigateTo({
    url: `/pages/post/detail/index?id=${postId}`,
  })
}

// 跳转到发布页
function goToPublish() {
  uni.navigateTo({
    url: '/pages/post/publish/index',
  })
}

// 加载帖子数据
async function loadPosts() {
  try {
    const res = await getPostList({
      keyword: searchKeyword.value,
      categoryId: currentCategory.value,
      page: page.value,
      pageSize: 10,
    })

    const items = res.data.list.map(post => ({
      ...post,
      images: post.images ? post.images.split(',') : [],
      commentCount: post.commentCount || 0,
      username: post.user?.nickname || '未知用户',
      createTime: new Date(post.createdAt).toLocaleDateString(),
    }))

    posts.value = page.value === 1 ? items : [...posts.value, ...items]
    hasMore.value = items.length === 10
  }
  catch (error) {
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })
  }
}

// 加载更多
function loadMore() {
  if (!hasMore.value)
    return
  page.value++
  loadPosts()
}

// 点赞/取消点赞
async function handleLike(postId: number) {
  try {
    const post = posts.value.find(p => p.id === postId)
    if (!post)
      return

    if (post.isLiked) {
      await unlikePost(postId)
      post.likes--
    }
    else {
      await likePost(postId)
      post.likes++
    }
    post.isLiked = !post.isLiked
  }
  catch (error) {
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none',
    })
  }
}
// 页面加载时获取数据
onMounted(() => {
  loadPosts()
})
</script>

<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <input
        v-model="searchKeyword"
        type="text"
        placeholder="搜索帖子"
        @confirm="handleSearch"
      >
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <view
        v-for="item in categories"
        :key="item.id"
        class="nav-item"
        :class="{ active: currentCategory === item.id }"
        @click="selectCategory(item.id)"
      >
        {{ item.name }}
      </view>
    </view>

    <!-- 帖子列表 -->
    <view class="post-list">
      <view v-for="post in posts" :key="post.id" class="post-item" @click="goToDetail(post.id)">
        <view class="post-header">
          <image src="../../../static/avatar.jpg" mode="aspectFill" class="avatar" />
          <view class="user-info">
            <text class="username">
              {{ post.username }}
            </text>
            <text class="time">
              {{ post.createTime }}
            </text>
          </view>
        </view>

        <view class="post-content">
          <text class="title">
            {{ post.title }}
          </text>
          <text class="content">
            {{ post.content }}
          </text>
          <view v-if="post.images && post.images.length" class="image-list">
            <image
              v-for="(image, index) in post.images"
              :key="index"
              :src="image"
              mode="aspectFill"
              class="content-image"
            />
          </view>
        </view>

        <view class="post-footer" @click.stop="handleLike(post.id)">
          <view class="action-item">
            <uni-icons :type="post.isLiked ? 'hand-up-filled' : 'hand-up'" size="24" color="#666" />
            <text class="count">
              {{ post.likes }}
            </text>
          </view>
          <view class="action-item">
            <uni-icons type="chat" size="24" color="#666" />
            <text class="count">
              {{ post.commentCount }}
            </text>
          </view>
          <view class="action-item">
            <uni-icons type="eye" size="24" color="#666" />
            <text class="count">
              {{ post.views }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="posts.length === 0" class="empty-tip">
      <text>暂无相关帖子</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text>加载更多</text>
    </view>

    <!-- 发布按钮 -->
    <view class="publish-btn" @click="goToPublish">
      <uni-icons type="plusempty" size="24" color="#fff" />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.search-bar {
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  input {
    width: 100%;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
  }
}

.category-nav {
  display: flex;
  background: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow-x: auto;

  .nav-item {
    padding: 10rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    background: #f5f5f5;
    border-radius: 28rpx;
    margin-right: 20rpx;
    white-space: nowrap;

    &.active {
      color: #fff;
      background: #4caf50;
    }
  }
}

.post-list {
  .post-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .post-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .user-info {
        flex: 1;

        .username {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 6rpx;
          display: block;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .post-content {
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
        display: block;
      }

      .content {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 20rpx;
        display: block;
      }

      .image-list {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10rpx;

        .content-image {
          width: calc(33.33% - 20rpx);
          height: 200rpx;
          margin: 10rpx;
          border-radius: 8rpx;
        }
      }
    }

    .post-footer {
      display: flex;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1px solid #eee;

      .action-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
          font-size: 36rpx;
          color: #999;
          margin-right: 10rpx;
        }

        .count {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

.empty-tip {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin-top: 200rpx;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
  color: #666;
  font-size: 28rpx;
}

.publish-btn {
  position: fixed;
  right: 40rpx;
  bottom: 200rpx;
  width: 100rpx;
  height: 100rpx;
  background: #4caf50;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(76, 175, 80, 0.3);

  .iconfont {
    font-size: 48rpx;
    color: #fff;
  }
}
</style>
